import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'


//引入仓库
import store from '../store'

//封装一个判断当前模块是否有权限的方法
function hasUrl(url: any, next: any) {
  //判断当前地址是否在信息menus数组中，如果在就next，如果不在就拦截并跳转首页
  let result = store.getters.getUser.menus_url.some((item: any) => url === item)
  if (result) {
    next()
  } else {
    next('/home')
  }
}

export const IndexRouter = [
  {
    path: '/menu',
    component: () => import('../views/menu/menu.vue'),
    meta: {
      title: '菜单管理'
    },
    beforeEnter(to: any, from: any, next: any) {
      hasUrl('/menu', next)
    }
  },
  {
    path: '/role',
    component: () => import('../views/role/role.vue'),
    meta: {
      title: '角色管理'
    },
    beforeEnter(to: any, from: any, next: any) {
      hasUrl('/role', next)
    }
  },
  {
    path: '/user',
    component: () => import('../views/user/user.vue'),
    meta: {
      title: '管理员管理'
    },
    beforeEnter(to: any, from: any, next: any) {
      hasUrl('/user', next)
    }
  },
  {
    path: '/cate',
    component: () => import('../views/cate/cate.vue'),
    meta: {
      title: '商品分类'
    }
  },
  {
    path:'/specss',
    component:()=>import('../views/specss/specss.vue'),
    meta:{
      title:'商品规格'
    }
  },
  {
    path:'/goods',
    component:()=>import('../views/goods/goods.vue'),
    meta:{
      title:'商品管理'
    }
  },
  {
    path:'/member',
    component:()=>import('../views/member/member.vue'),
    meta:{
      title:'会员管理'
    }
  },
  {
    path:'/banner',
    component:()=>import('../views/banner/banner.vue'),
    meta:{
      title:'轮播图列表'
    }
  },
  {
    path:'/seck',
    component:()=>import('../views/seck/seck.vue'),
    meta:{
      title:'活动列表'
    }
  }
]

const routes: Array<RouteRecordRaw> = [
  {
    path: '',
    redirect: '/index'
  },
  {
    path: '/login',
    component: () => import('../pages/login.vue')
  },
  {
    path: '/index',
    component: () => import('../pages/index.vue'),
    children: [
      {
        path: '',
        redirect: '/home'
      },
      {
        path: '/home',
        component: () => import('../views/home.vue')
      },
      ...IndexRouter
    ]
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 封装全局登陆事件
router.beforeEach((to, from, next) => {
  //先检测用户访问的地址是否登录
  if (to.path == '/login') {
    next()
    return
  }
  //判断用户是否登录
  if (store.getters.getUser) {
    next()
    return
  }
  //如果未登录 就强制跳转登录页
  next('/login')
})

export default router
